<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>分类列表</span>
		</div>
		<el-tree :data="data" :props="defaultProps">
			<!-- 作用域插槽 ；{ node, data }是解构得到，node是节点对象，data是渲染的数据对象-->
			<span class="custom-tree-node" slot-scope="{ node, data }">
				<span>{{ node.label }}</span>
				<span>
					<!-- .stop阻止事件冒泡 ，防止点击时自动展开-->
					<el-button type="text" icon="el-icon-edit" @click.stop="openEditDialog(node,data)"
						:disabled="data.cate_id === 0">编辑</el-button>
					<el-button type="text" icon="el-icon-circle-plus-outline" @click.stop="openInsertDialog(node,data)">
						添加
					</el-button>
					<el-button type="text" icon="el-icon-delete" @click.stop="handleRemove(node,data)"
						:disabled="data.cate_id === 0">删除
					</el-button>
				</span>
			</span>
		</el-tree>

		<!-- 添加分类 -->
		<el-dialog title="添加分类" :visible.sync="insert_dialog_visible" @close="handleCloseDialog('insert_form')">
			<el-form :model="insert_form" ref="insert_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="分类名称:" prop="cate_name">
					<el-input type="text" v-model="insert_form.cate_name" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="insert_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleInsert">添加</el-button>
			</span>
		</el-dialog>

		<!-- 编辑分类 -->
		<el-dialog title="编辑分类" :visible.sync="edit_dialog_visible" @close="handleCloseDialog('edit_form')">
			<el-form :model="edit_form" ref="edit_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="分类名称:" prop="cate_name">
					<el-input type="text" v-model="edit_form.cate_name" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="edit_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleEdit">保存</el-button>
			</span>
		</el-dialog>
	</el-card>
</template>

<script>
	import { Category } from "@/api";
	import axios from "axios";
	export default {
		name: 'List',
		data() {
			return {
				data: [],
				defaultProps: {
					/* 根据返回的数据 */
					children: 'children',
					label: 'cate_name',
				},
				insert_dialog_visible: false,
				insert_form: {
					cate_name: '',
					parent_id: '',
				},
				rules: {
					cate_name: [{ required: true, message: "请填写分类名称！", trigger: 'blur' }]
				},
				// 当前操作的 node
				current_node: '',
				edit_dialog_visible: false,
				edit_form: {
					cate_name: '',
					parent_id: '',
				},
			};
		},
		mounted() {
			document.title = "分类页面";
			// 加载所有分类
			this.loadCategory();
		},
		methods: {
			async loadCategory() {
				// 返回的数据是tree类型，若是扁平化数据需要转为tree类型
				let { status, msg, data } = await Category.list({ type: 'tree' });
				if (status) {
					this.data = [{
						cate_id: 0,
						cate_name: "全部分类",
						children: data,
					}];
				}
			},
			// 关闭弹窗，清除表单验证状态
			handleCloseDialog(formName) {
				// formName是变量，不能使用 ref.formName
				this.$refs[formName].resetFields();
			},
			// 打开添加分类弹窗
			openInsertDialog(node, data) {
				// 缓存当前操作的 node
				this.current_node = node;
				// 转存parent_id
				this.insert_form.parent_id = data.cate_id;
				this.insert_dialog_visible = true;
			},
			// 添加分类
			handleInsert() {
				this.$refs.insert_form.validate(async (valid) => {
					if (valid) {
						let { status, msg, data } = await Category.add({ ...this.insert_form });
						if (status) {
							// 操作DOM
							let new_child = { ...this.insert_form, ...data };
							let node_data = this.current_node.data;
							if (!node_data.children) {
								this.$set(node_data, 'children', []);
							}
							node_data.children.push(new_child);
							// 关闭弹窗
							this.insert_dialog_visible = false;
							// 信息提示
							this.$message.success(msg);
						} else {
							this.$message.error(msg);
						}
					}
				});
			},
			// 打开编辑弹窗
			openEditDialog(node, data) {
				// 缓存当前操作的 node
				this.current_node = node;
				// 还原表单
				this.edit_form = { ...data };
				this.edit_dialog_visible = true;
			},
			// 编辑分类
			handleEdit() {
				// 表单验证
				this.$refs.edit_form.validate(async (valid) => {
					if (valid) {
						let { status, msg } = await Category.edit({ ...this.edit_form });
						if (status) {
							// 操作DOM：让vue知道我们修改了数据，后续vue会自动虚拟DOM、对比等操作，从而实现数据的更新
							this.current_node.data = { ...this.edit_form };
							/* 写法2： Object.assign(this.current_node.data, this.edit_form); */
							// 关闭弹窗
							this.edit_dialog_visible = false;
							// 添加成功信息提示
							this.$message.success(msg);
						} else {
							// 添加失败信息提示
							this.$message.error(msg);
						}
					}
				});
			},
			// 删除分类
			handleRemove(node, data) {
				let { cate_id } = data;
				// 判断是否拥有子级分类
				if (data.children && data.children.length) {
					this.$message.error("拥有子级分类无法删除！");
					return;
				}
				this.$confirm('此操作将永久删除该分类, 是否继续?', '警告', { type: 'warning' })
					.then(async () => {
						let { status, msg } = await Category.remove({ cate_id });
						if (status) {
							// 操作 DOM
							const parent = node.parent;
							const children = parent.data.children || parent.data;
							const index = children.findIndex(child => child.cate_id === data.cate_id);
							children.splice(index, 1);
							// 信息提示
							this.$message.success(msg);
						} else {
							// 信息提示
							this.$message.error(msg);
						}
					}).catch(() => {
						this.$message.info('已取消删除！');
					});
			}

		},
	};
</script>

<style>
	.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 8px;
	}
</style>
